<!--
  * 计划站位表信息
  *
  * @Author:    lmabbe
  * @Date:      2025-06-27 19:10:13
  * @Copyright  lmabbe
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form" size="small">
    <a-row class="smart-query-form-row">
      <a-form-item class="smart-query-form-item" label="物料类型">
        <SmartEnumSelect
          v-model:value="queryForm.materialType"
          size="small"
          enum-name="WORK_ORDER_PRODUCTION_PLAN_POSITION_MATERIAL_TYPE_ENUM"
          placeholder="请选择物料类型"
          width="200px"
        />
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="物料信息查询">
        <a-input v-model:value="queryForm.materialKeywords" placeholder="可查询物料编号/名称/描述/规格" style="width: 200px" />
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="机器信息查询">
        <a-select v-model:value="queryForm.machineId" :allowClear="true" :style="`width: 200px`" placeholder="机器信息查询">
          <a-select-option v-for="item in machineInfoData" :key="item.machineId" :value="item.machineId">
            {{ item.machineName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="站位信息查询">
        <a-input v-model:value="queryForm.positionKeywords" placeholder="站位信息查询" style="width: 200px" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button class="smart-margin-left10" @click="resetQuery">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <!---------- 表格操作行 begin ----------->
  <a-row class="smart-table-btn-block">
    <div class="smart-table-operate-block">
      <a-button v-privilege="'productionPlanPosition:add'" :disabled="planInfoRef?.postedFlag" size="small" type="primary" @click="showForm">
        <template #icon>
          <PlusOutlined />
        </template>
        新建
      </a-button>
      <a-upload
        v-privilege="'productionPlanPosition:importPosition'"
        :beforeUpload="importPosition"
        :disabled="planInfoRef?.postedFlag"
        :max-count="1"
        :show-upload-list="false"
        accept=".xls,.xlsx"
        size="small"
      >
        <a-button :disabled="planInfoRef?.postedFlag" size="small">
          <CloudUploadOutlined />
          导入站位表
        </a-button>
      </a-upload>
    </div>
  </a-row>
  <!---------- 表格操作行 end ----------->

  <!---------- 表格 begin ----------->
  <a-table
    :columns="columns"
    :dataSource="tableData"
    :loading="tableLoading"
    :pagination="false"
    :scroll="{ y: 360 }"
    bordered
    rowKey="planPositionId"
    size="small"
  >
    <template #bodyCell="{ text, record, column }">
      <template v-if="column.dataIndex === 'materialType'">
        <span>{{ $smartEnumPlugin.getDescByValue('WORK_ORDER_PRODUCTION_PLAN_POSITION_MATERIAL_TYPE_ENUM', text) }}</span>
      </template>

      <template v-if="column.dataIndex === 'action'">
        <div class="smart-table-operate">
          <a-button v-privilege="'productionPlanPosition:update'" :disabled="planInfoRef?.postedFlag" type="link" @click="showForm(record)"
            >编辑
          </a-button>
          <a-button v-privilege="'productionPlanPosition:delete'" :disabled="planInfoRef?.postedFlag" danger type="link" @click="onDelete(record)"
            >删除
          </a-button>
        </div>
      </template>
    </template>
  </a-table>
  <!---------- 表格 end ----------->

  <div class="smart-query-table-page">
    <a-pagination
      v-model:current="queryForm.pageNum"
      v-model:pageSize="queryForm.pageSize"
      :defaultPageSize="queryForm.pageSize"
      :pageSizeOptions="PAGE_SIZE_OPTIONS"
      :show-total="(total) => `共${total}条`"
      :total="total"
      show-less-items
      showQuickJumper
      showSizeChanger
      @change="queryData"
      @showSizeChange="queryData"
    />
  </div>

  <ProductionPlanPositionForm ref="formRef" @reloadList="queryData" />
</template>
<script setup>
  import { reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { productionPlanPositionApi } from '/@/api/business/product/order/production-plan-position-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import ProductionPlanPositionForm from './production-plan-position-form.vue';
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
  import { machineInfoApi } from '/@/api/business/product/machine/machine-info-api.js';
  // ---------------------------- 表格列 ----------------------------

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '计划站位ID',
      dataIndex: 'planPositionId',
      ellipsis: true,
      width: 0,
    },
    {
      title: '计划ID',
      dataIndex: 'planId',
      ellipsis: true,
      width: 0,
    },
    {
      title: '站位表站位',
      dataIndex: 'stationTablePosition',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '机器站位ID',
      dataIndex: 'positionId',
      ellipsis: true,
      width: 0,
    },
    {
      title: '系统中站位',
      dataIndex: 'systemRealPosition',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '机器ID',
      dataIndex: 'machineId',
      ellipsis: true,
      width: 0,
    },
    {
      title: '机器名称',
      dataIndex: 'machineName',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '主料编码',
      dataIndex: 'mainMaterialCode',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '物料类型',
      dataIndex: 'materialType',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '物料规格',
      dataIndex: 'materialSpec',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '物料描述',
      dataIndex: 'materialDesc',
      ellipsis: true,
      width: '200px',
      align: 'center',
    },

    {
      title: '物料单位',
      dataIndex: 'materialUnit',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '用量',
      dataIndex: 'dosage',
      ellipsis: true,
      width: '60px',
      align: 'center',
    },
    {
      title: '位置',
      dataIndex: 'location',
      ellipsis: true,
      width: '200px',
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      width: '200px',
      align: 'center',
    },
    {
      title: '禁用状态',
      dataIndex: 'disabledFlag',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '更新人',
      dataIndex: 'updateUserName',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 100,
      align: 'center',
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    planId: undefined,
    materialType: undefined, //物料类型:[1:主料，2:替代料]
    materialKeywords: undefined, //物料信息查询
    machineId: undefined, //机器ID
    positionKeywords: undefined, //站位信息查询
    pageNum: 1,
    pageSize: 10,
  };
  // 查询表单form
  const queryForm = reactive({ ...queryFormState });
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      let queryResult = await productionPlanPositionApi.queryPage(queryForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref();

  function showForm(data) {
    data['planId'] = queryForm.planId;
    data['lineId'] = planInfoRef.value.lineId;
    formRef.value.show(data);
  }

  // ---------------------------- 单个删除 ----------------------------
  //确认删除
  function onDelete(data) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestDelete(data);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  //请求删除
  async function requestDelete(data) {
    SmartLoading.show();
    try {
      let deleteForm = {
        goodsIdList: selectedRowKeyList.value,
      };
      await productionPlanPositionApi.delete(data.planPositionId);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([]);

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
  }

  // 批量删除
  function confirmBatchDelete() {
    Modal.confirm({
      title: '提示',
      content: '确定要批量删除这些数据吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestBatchDelete();
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  //请求批量删除
  async function requestBatchDelete() {
    try {
      SmartLoading.show();
      await productionPlanPositionApi.batchDelete(selectedRowKeyList.value);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  const planInfoRef = ref();

  function setPlanInfo(planInfo) {
    queryForm.planId = planInfo.planId;
    planInfoRef.value = planInfo;
    onSearch();
    loadMachineInfoData();
  }

  const machineInfoData = ref();

  function loadMachineInfoData() {
    let param = {
      belongLineId: planInfoRef.value.lineId,
    };
    machineInfoApi.all(param).then((res) => {
      machineInfoData.value = res.data;
    });
  }

  const importPositionParam = reactive({});

  async function importPosition(file) {
    // 检查文件类型
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';

    if (!isExcel) {
      message.error('只能上传Excel文件!');
      return false;
    }

    SmartLoading.show();
    try {
      let param = {
        planId: planInfoRef.value.planId,
      };

      await productionPlanPositionApi.importPosition(file, param).then((res) => {
        onSearch();
        message.success('导入成功');
        SmartLoading.hide();
      });
    } finally {
      SmartLoading.hide();
    }
    // 返回false阻止默认上传行为
    return false;
  }

  defineExpose({
    setPlanInfo,
  });
</script>
